const express = require("express");
const router = express.Router();
const models = require("../models");
const Op = models.Sequelize.Op; // 模糊查询的时候需要用到

// 查询社团申请列表
router.get("/list", async function (req, res, next) {
  const where = {};
  const where2 = {};
  const status = req.query.status;
  const name = req.query.name;
  const applyType = req.query.applyType;
  const checkPerson = req.query.checkPerson;
  const personType = req.query.personType;
  if (status) {
    if (status == 0) {
      where.status = {
        [Op.like]: status,
      };
    } else {
      where.status = {
        [Op.gte]: status, // gte 大于等于
      };
    }
  }
  if (name) {
    where2.name = {
      [Op.like]: "%" + name + "%",
    };
  }
  if (applyType) {
    where.applyType = {
      [Op.like]: applyType,
    };
  } else {
    // president--社团部长查看列表，  admin--管理员查看列表
    if (personType == "admin") {
      where.applyType = {
        [Op.lte]: 4,
      };
    } else if (personType == "president") {
      where.applyType = {
        [Op.gte]: 5,
      };
    }
  }

  if (checkPerson) {
    where.checkPerson = {
      [Op.like]: checkPerson,
    };
  }
  const currentPage = parseInt(req.query.currentPage) || 1; // 分页参数
  const pageSize = parseInt(req.query.pageSize) || 10; // 分页参数
  const result = await models.SocietyApply.findAndCountAll({
    attributes: [
      "name",
      "introduce",
      "planNum",
      "publicizeUrl",
      "reason",
      "status",
      "attachment",
      "createdAt",
      "updatedAt",
      "checkPerson",
      "applyType",
      "personId",
      "type",
      "remark",
      "id",
    ],
    include: [
      {
        attributes: ["username", "name", "stuCode", "phone", "role", "gender"],
        model: models.User,
        where: where2,
        include: [
          {
            attributes: ["name"],
            model: models.College,
          },
          {
            attributes: ["name"],
            model: models.Major,
          },
          {
            attributes: ["name"],
            model: models.Grade,
          },
        ],
      },
    ],
    offset: (currentPage - 1) * pageSize,
    limit: pageSize,
    where: where,
    order: [["updatedAt", "asc"]], // 根据某个字段进行排序， desc-降序 asc-升序
  });
  res.json({
    code: 200,
    msg: "操作成功",
    data: {
      total: result.count,
      currentPage: currentPage,
      pageSize: pageSize,
      data: result.rows,
    },
  });
});

// 修改社团申请
router.put("/", async function (req, res, next) {
  const result = await models.SocietyApply.findByPk(req.body.id);
  result.update(req.body);
  res.json({
    code: 200,
    msg: "操作成功",
  });
});

// 新增社团申请
router.post("/create", async function (req, res, next) {
  const where = {};
  const personId = req.body.personId;
  where.personId = {
    [Op.like]: personId,
  };
  const data = await models.SocietyApply.findAndCountAll({
    where: where,
  });
  if (data && data.rows.length > 0) {
    let status1 = 0;
    let status2 = 0;
    data.rows.forEach((item) => {
      if (item.applyType == 1) {
        status1 += item.status;
      } else if (item.applyType == 2) {
        status2 += item.status;
      }
    });
    if (req.body.applyType == 1) {
      if (status1 == 0) {
        res.json({
          code: 400,
          msg: "已有待审批的建社申请待审批，暂时无法再次提交",
        });
        return;
      } else if (status1 == 1) {
        res.json({
          code: 400,
          msg: "你已经是一个社团的社长，不能再次创建社团",
        });
        return;
      } else {
        models.SocietyApply.create({
          personId: req.body.personId,
          name: req.body.name,
          reason: req.body.reason,
          planNum: req.body.planNum,
          attachment: req.body.attachment,
          introduce: req.body.introduce,
          publicizeUrl: req.body.publicizeUrl,
          status: 0,
          type: req.body.type,
          applyType: req.body.applyType,
        });
      }
    } else if (req.body.applyType == 2) {
      if (status2 == 0) {
        res.json({
          code: 400,
          msg: "已有待审批的修改申请待审批，暂时无法再次提交",
        });
        return;
      } else {
        models.SocietyApply.create({
          personId: req.body.personId,
          name: req.body.name,
          reason: req.body.reason,
          planNum: req.body.planNum,
          attachment: req.body.attachment,
          introduce: req.body.introduce,
          publicizeUrl: req.body.publicizeUrl,
          status: 0,
          type: req.body.type,
          applyType: req.body.applyType,
        });
      }
    }
  } else {
    models.SocietyApply.create({
      personId: req.body.personId,
      name: req.body.name,
      reason: req.body.reason,
      planNum: req.body.planNum,
      attachment: req.body.attachment,
      introduce: req.body.introduce,
      publicizeUrl: req.body.publicizeUrl,
      status: 0,
      type: req.body.type,
      applyType: req.body.applyType,
    });
  }
  res.json({
    code: 200,
    msg: "操作成功",
  });
});

// 审批社团申请
router.put("/check", async function (req, res, next) {
  // 同意
  if (req.body.status == 1) {
    const applyType = Number(req.body.applyType);
    const id = req.body.id;
    const result = await models.SocietyApply.findByPk(req.body.id);
    result.update(req.body);
    // 1是创建社团
    if (applyType === 1) {
      // 创建社团
      models.Society.create({
        name: result.name,
        introduce: result.introduce,
        nowNumber: 1,
        planNumber: result.planNum,
        minister: result.personId,
        type: result.type,
        imgurl: result.publicizeUrl,
        status: 0, // 默认创建就开始招新
      }).then(() => {
        const where2 = {};
        where2.name = {
          [Op.like]: "魔术爱好者协会",
        };
        // 审批成功之后设置用户的社团id
        models.Society.findAndCountAll({
          where: where2,
        }).then((res) => {
          models.User.findByPk(res.rows[0].minister).then((result3) => {
            const result = result3;
            result.update({ society: "-" + res.rows[0].id + "-", role: 1 });
          });
        });
      });
    } else if (applyType === 2) {
      let where = {};
      const minister = result.personId;
      where.minister = {
        [Op.like]: minister,
      };
      models.Society.findAndCountAll({
        where: where,
      }).then((res2) => {
        res2.rows[0].update({
          name: result.name,
          introduce: result.introduce,
          planNumber: result.planNum,
          type: result.type,
          imgurl: result.publicizeUrl,
        });
      });
    }
    // 3是解散社团
    else if (applyType === 3) {
      models.SocietyApply.findByPk(id).then((res1) => {
        models.User.findByPk(res1.personId).then((res2) => {
          const society = res2.society;
          const where = {};
          where.society = {
            [Op.like]: "%" + society + "%",
          };
          models.User.findAndCountAll({ where: where }).then((res3) => {
            return res.json({
              code: 200,
              msg: "操作成功",
            });
          });
        });
      });
    }
    // 4是社团换届申请
    else if (applyType === 4) {
      models.SocietyApply.findByPk(id).then((res1) => {
        const username = res1.introduce;
        models.User.findByPk(res1.personId).then((res2) => {
          const society = res2.society;
          res2.update({ society: null, role: 0 });
          const where2 = {};
          where2.username = {
            [Op.like]: username,
          };
          models.User.findAndCountAll({
            where: where2,
          }).then((res3) => {
            res3.rows[0].update({ society: society, role: 1 });
          });
        });
      });
    }
  }
  // 驳回
  else {
    const result = await models.SocietyApply.findByPk(req.body.id);
    result.update(req.body);
  }
  res.json({
    code: 200,
    msg: "操作成功",
  });
});

// 新增入团/退团申请
router.post("/join", async function (req, res, next) {
  const where = {};
  const personId = req.body.personId || "";
  const applyType = Number(req.body.applyType);
  const checkPerson = req.body.checkPerson || "";
  const username = req.body.username || "";
  const reason = req.body.reason || "";
  if (personId) {
    where.personId = {
      [Op.like]: personId,
    };
  }
  if (applyType) {
    where.applyType = {
      [Op.like]: applyType,
    };
  }
  if (checkPerson) {
    where.checkPerson = {
      [Op.like]: checkPerson,
    };
  }
  const data = await models.SocietyApply.findAndCountAll({
    where: where,
  });
  let status = 0;
  let params = {};
  if (applyType == 5) {
    params = {
      personId: personId,
      status: 0,
      applyType: applyType,
      checkPerson: checkPerson,
    };
  } else if (applyType == 4) {
    params = {
      personId: personId,
      status: 0,
      applyType: applyType,
      introduce: username,
      reason: reason,
    };
  } else if (applyType == 3) {
    params = {
      personId: personId,
      status: 0,
      applyType: applyType,
      reason: reason,
    };
  }
  if (data && data.rows.length > 0) {
    data.rows.forEach((item) => {
      status += item.status;
    });
    if (Number(status) === 0) {
      res.json({
        code: 402,
        msg: "已提交该类申请，请耐心等待审批",
      });
    } else if (Number(status) === 1) {
      let msg = "";
      if (applyType == 5) {
        msg = "你已是该社团成员";
      } else if (applyType == 4) {
        msg = "你已完成社团换届";
      }
      res.json({
        code: 402,
        msg: msg,
      });
    } else {
      models.SocietyApply.create(params);
      res.json({
        code: 200,
        msg: "申请提交成功，等待审批中",
      });
    }
  } else {
    models.SocietyApply.create(params);
    res.json({
      code: 200,
      msg: "申请提交成功，等待审批中",
    });
  }
});

// 审批入团/退团申请
router.post("/check", async function (req, res, next) {
  const personId = req.body.personId || "";
  const applyType = req.body.applyType || "";
  const applyStatus = req.body.applyStatus || 0;
  const id = req.body.id || "";
  const society = req.body.society || "";
  // 3是解散社团
  if (Number(applyType) === 3) {
    const newMinster = introduce.split("-");
  }
  // 4是社团换届申请
  else if (Number(applyType) === 4) {
    const newMinster = introduce.split("-");
  }
  // 5是入团申请
  else if (Number(applyType) === 5) {
    if (applyStatus == 1) {
      models.SocietyApply.findByPk(id).then((result1) => {
        result1.update({ status: 1 });
      });
      models.User.findByPk(personId).then((result2) => {
        result2.update({
          society: result2.society
            ? result2.society + society + "-"
            : "-" + society + "-",
        });
      });
    } else {
      models.SocietyApply.findByPk(id).then((result1) => {
        result1.update({ status: 2 });
      });
    }
  }
  // 6是退出社团申请
  else if (applyType == 6) {
    console.log(
      "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa____________________________"
    );
  }
  res.json({
    code: 200,
    msg: "审批成功",
  });
});

module.exports = router;
